package cn.wygandwdn.core.transport.server.handler;

import cn.wygandwdn.common.factory.SingletonFactory;
import cn.wygandwdn.common.message.RpcRequest;
import cn.wygandwdn.common.message.RpcResponse;
import cn.wygandwdn.core.cache.RequestCache;
import cn.wygandwdn.core.config.Config;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description:
 * @author: WYG
 * @time: 2021/10/27 16:05
 */

public class RpcServerHandler extends SimpleChannelInboundHandler<RpcRequest> {

    private static final Logger log = LoggerFactory.getLogger(RpcServerHandler.class);

    private final RequestHandler requestHandler;
    private final RequestCache cache;

    public RpcServerHandler() {
        this.requestHandler = SingletonFactory.getInstance(RequestHandler.class);
        this.cache = Config.getCache();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest msg) throws Exception {
        log.debug("收到客户端请求: {}", msg);
        if (cache.contains(msg.getSequenceId())) {
            log.debug("收到重复请求,请求详细信息: {}", msg);
            return;
        }
        cache.put(msg.getSequenceId(), Boolean.TRUE);
        RpcResponse response = requestHandler.handle(msg);
        if (ctx.channel().isActive() && ctx.channel().isWritable()) {
            ctx.writeAndFlush(response);
        } else {
            log.error("通道不可写");
        }
    }

}
